package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Common"
	"encoding/json"
)

//实体列表
type EntityDetaiData struct {
    EntitySet string `db:"Fentity_set" json:"entity_set"`
    EntityDesc string `db:"Fdesc" json:"entity_desc"`
    EntityName string `db:"Fname" json:"entity_name"`
}

type DisplayEntityDetailCgi struct {
	Common.CgiBase
	DbEntity []EntityDetaiData
}

func (cgi *DisplayEntityDetailCgi)quertEntityDetail() (bool) {
	if cgi.Input["user"] == "" {
		sql := "select Fentity_set,Fdesc,Fname from db_entity_set_data where Fname=?;"
		err := Databases.Db.Select(&cgi.DbEntity, sql, cgi.Input["name"])
		if err != nil {
			fmt.Println("exec failed, ", err)
			return false
		}
	    return true
	} else {
		sql := "select Fentity_set,Fname from db_entity_suggest where Fname=? and Fuser=?;"
		err := Databases.Db.Select(&cgi.DbEntity, sql, cgi.Input["name"], cgi.Input["user"])
		if err != nil {
			fmt.Println("exec failed, ", err)
			return false
		}
	    return true
	}
}

func (cgi *DisplayEntityDetailCgi)transformEntity() (string){
    str, _ := json.Marshal(cgi.DbEntity[0])
    str_res := string(str)
    return str_res
}

func (cgi *DisplayEntityDetailCgi)processParam(c *gin.Context) {
	cgi.Input["name"] = c.Query("name")
	cgi.Input["user"] = c.DefaultQuery("user", "")
}

func DisplayEntityDetail(c *gin.Context) {
	var cgi DisplayEntityDetailCgi
	cgi.Init(c)
	cgi.processParam(c)

	res := cgi.quertEntityDetail()
	if (!res) {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "query fail",
	        "data": "{}",
	    })
	    return
	}

	if len(cgi.DbEntity) < 1 {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "no data",
	        "data": "{}",
	    })
		fmt.Println("no data")
		return	
	}

	json_res := cgi.transformEntity()

    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": json_res,
    })

}

